package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    //登入
    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse response){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        //从redis获取验证码
        String validataCodeInRdies = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (validataCodeInRdies!=null&&validateCode!=null&&validateCode.equals(validataCodeInRdies)){
            //验证成功
            //判断输入的手机号是否为会员
            Member member = memberService.findByTelephone(telephone);
            if (member==null){
                //不是会员，自动完成注册
                member = new Member();  //记得new，否则容易空指针
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.add(member);

            }
            /**
             * todo  加密未完成
             */


            //向客户端浏览器写入Cookie，内容为手机号
            Cookie cookie = new Cookie("login_member_telephone",telephone);

            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);

            //保存会员信息到Redis中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,json);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }


    //查看会员信息
    @RequestMapping("/getMember")
    public Result getMember(HttpServletResponse response, HttpServletRequest request){
        //1.使用cookie获取当前用户标识，获取手机号码
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            //2.判断获取的cookie是否正确
            if ("login_member_telephone".equals(cookie.getName())){
                //3.获取cookie对象中的value，进行写出
                String value = cookie.getValue();
                System.out.println("手机号码为："+value);
                //4.根据cookie对象的value（在数据库中根据手机号码查询会员信息）
                Member member = memberService.findByTelephone(value);
                //5.查询成功，返回会员信息给html页面回显
                return new Result(true,MessageConstant.GET_MEMBER_LIST_SUCCESS,member);
            }
        }
        //查询失败
        return new Result(false,MessageConstant.GET_MEMBER_LIST_FAIL);
    }

    @RequestMapping("/editMember")
    public Result editMember(@RequestBody Member member){

        try {
            memberService.editMember(member);
            return new Result(true,MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_MEMBER_FAIL);
        }

    }

    //测试
    public void test(){
         /*   try {
            //模拟数据测试
            Member member = new Member();//创建会员对象，进行存储
            member.setPhoneNumber("18770397149");
            member.setName("胡帅");
            member.setPassword("123456");
            member.setSex("1");

            return new Result(true,MessageConstant.GET_MEMBER_LIST_SUCCESS,member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_LIST_FAIL);
        }*/
    }

}
